home *** CD-ROM | disk | FTP | other *** search
/ Java Developer's Companion / Java Developer's Companion.iso / documentation / tutorial / intl / datamgmt / demos-1.1 / MessageFormatDemo.java < prev    next >
Encoding:
Java Source  |  1997-07-13  |  13.8 KB  |  436 lines

  1. /*
  2.  * Copyright (c) 1995-1997 Sun Microsystems, Inc. All Rights Reserved.
  3.  *
  4.  * Permission to use, copy, modify, and distribute this software
  5.  * and its documentation for NON-COMMERCIAL purposes and without
  6.  * fee is hereby granted provided that this copyright notice
  7.  * appears in all copies. Please refer to the file "copyright.html"
  8.  * for further important copyright and licensing information.
  9.  *
  10.  * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
  11.  * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
  12.  * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
  13.  * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR
  14.  * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
  15.  * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
  16.  */
  17. /*
  18.  * @(#)MessageFormatDemo.java    1.4 97/06/27
  19.  *
  20.  * (C) Copyright Taligent, Inc. 1996 - All Rights Reserved
  21.  * (C) Copyright IBM Corp. 1996 - All Rights Reserved
  22.  *
  23.  * Portions copyright (c) 1996 Sun Microsystems, Inc. All Rights Reserved.
  24.  *
  25.  *   The original version of this source code and documentation is copyrighted
  26.  * and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These
  27.  * materials are provided under terms of a License Agreement between Taligent
  28.  * and Sun. This technology is protected by multiple US and International
  29.  * patents. This notice and attribution to Taligent may not be removed.
  30.  *   Taligent is a registered trademark of Taligent, Inc.
  31.  *
  32.  * Permission to use, copy, modify, and distribute this software
  33.  * and its documentation for NON-COMMERCIAL purposes and without
  34.  * fee is hereby granted provided that this copyright notice
  35.  * appears in all copies. Please refer to the file "copyright.html"
  36.  * for further important copyright and licensing information.
  37.  *
  38.  * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
  39.  * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
  40.  * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
  41.  * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR
  42.  * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
  43.  * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
  44.  *
  45.  */
  46.  
  47. import java.applet.Applet;
  48. import java.awt.*;
  49. import java.lang.*;
  50.  
  51. import java.util.*;
  52. import java.text.NumberFormat;
  53. import java.text.MessageFormat;
  54. import java.text.ChoiceFormat;
  55. import java.text.SimpleDateFormat;
  56.  
  57. import java.awt.event.KeyAdapter;
  58. import java.awt.event.KeyEvent;
  59.  
  60. import java.awt.event.WindowAdapter;
  61. import java.awt.event.WindowEvent;
  62.  
  63. import java.awt.event.ItemListener;
  64. import java.awt.event.ItemEvent;
  65.  
  66. /**
  67.  * <P> Pattern formats are used to put together sequences of strings, numbers,
  68.  * dates, and other formats to create messages.  The pattern formatters
  69.  * facilitate localization because they prevent both hard-coding of message
  70.  * strings, <I> and </I> hard-coding of the concatenation sequence for portions
  71.  * of message strings.  This means localizers can change the content, format,
  72.  * and order of any text as appropriate for any language.
  73.  * </P>
  74.  
  75.  * @see        java.util.Format
  76.  * @see        java.util.MessageFormat
  77.  * @version    1.4 06/27/97
  78.  * @author     Laura Werner, Mark Davis
  79. */
  80.  
  81. public class MessageFormatDemo extends DemoApplet
  82. {
  83.     /**
  84.      * The main function which defines the behavior of the MessageFormatDemo
  85.      * applet when an applet is started.
  86.      */
  87.     public static void main(String argv[]) {
  88.         DemoApplet.showDemo(new MessageFormatFrame(null));
  89.     }
  90.  
  91.     /**
  92.      * This creates a MessageFormatFrame for the demo applet.
  93.      */
  94.     public Frame createDemoFrame(DemoApplet applet) {
  95.         return new MessageFormatFrame(applet);
  96.     }
  97. }
  98.  
  99. /**
  100.  * A Frame is a top-level window with a title. The default layout for a frame
  101.  * is BorderLayout.  The MessageFormatFrame class defines the window layout of
  102.  * MessageFormatDemo.
  103.  */
  104.  class MessageFormatFrame extends Frame implements ItemListener {
  105.  
  106.     /**
  107.      * Constructs a new MessageFormatFrame that is initially invisible.
  108.      */
  109.     public MessageFormatFrame(DemoApplet applet)
  110.     {
  111.         super("Message Formatting Demo");
  112.         this.applet = applet;
  113.         init();
  114.  
  115.     // set up event handling
  116.     MyKeyAdapter keyListener = new MyKeyAdapter();
  117.         argText[0].addKeyListener(keyListener);
  118.         argText[1].addKeyListener(keyListener);
  119.         argText[2].addKeyListener(keyListener);
  120.         patternText.addKeyListener(keyListener);
  121.  
  122.     localeMenu.addItemListener(this);
  123.  
  124.     addWindowListener(new MyWindowAdapter());
  125.  
  126.         start();
  127.     }
  128.  
  129.     /**
  130.      * Initializes the applet. You never need to call this directly, it
  131.      * is called automatically by the system once the applet is created.
  132.      */
  133.     public void init() {
  134.  
  135.         //Get all locales for debugging, but only get G7 locales for demos.
  136.         if (DEBUG == true)
  137.              locales = NumberFormat.getAvailableLocales();
  138.         else locales = Utility.getG7Locales();
  139.  
  140.         buildGUI();
  141.  
  142.     }
  143.  
  144.     /**
  145.      * Called to start the applet. You never need to call this method
  146.      * directly, it is called when the applet's document is visited.
  147.      */
  148.     public void start() {
  149.  
  150.         // Stick some initial data into the controls....
  151.         argText[0].setText("3");
  152.         argText[1].setText("MyDisk");
  153.         argText[2].setText("3 Mar 96");
  154.  
  155.         patternText.setText("");
  156.         resetFormat();
  157.         doFormatting();
  158.     }
  159.  
  160.     /**
  161.      * Reset to the default message format using the ResourceBundle mechanism.
  162.      * @see java.util.ResourceBundle
  163.      * @see java.util.ListResourceBundle
  164.      */
  165.     public void resetFormat() {
  166.         Locale locale = locales[localeMenu.getSelectedIndex()];
  167.  
  168.         ResourceBundle choiceResources =
  169.              ResourceBundle.getBundle("ChoiceResource", locale);
  170.  
  171.     patternText.setText(choiceResources.getString("patternText"));
  172.     }
  173.  
  174.  
  175.     /**
  176.      * Create a new format based on the selection changes and update the
  177.      * output text area.
  178.      */
  179.     public void doFormatting() {
  180.  
  181.         // Now create the Message Formatter itself
  182.         MessageFormat format = new MessageFormat(patternText.getText());
  183.  
  184.         format.setLocale(locales[localeMenu.getSelectedIndex()]);
  185.  
  186.         // Create the array of objects to format....
  187.         Object[] objects = new Object[3];
  188.  
  189.         for(int i=0; i<objects.length; i++ ) {
  190.              try {
  191.                 // Try parsing as a Date
  192.                 // LAURA Must do this first, because most dates start with
  193.                 // something that looks like a Double.
  194.  
  195.                 // 1 millisecond is added to display the date correctly.
  196.                 // This is done to fix the following scenario, eg,
  197.                 // "27 Sept 96" ==> "26 Sept 96 12:00 AM PDT" which is
  198.                 // equvalent to "27 Sept 96 00:00 AM PDT".
  199.         SimpleDateFormat dateFormat = new SimpleDateFormat("dd MMM yy");
  200.                 objects[i]
  201.                     = new Date((dateFormat.parse(argText[i].getText())).getTime()+1);
  202. /*
  203.                 objects[i]
  204.                     = new Date((new Date(argText[i].getText())).getTime()+1);
  205. */
  206.             } catch( Exception e ) {
  207.                try{
  208.                     // Try parsing as a Double
  209.                     objects[i] = new Double( argText[i].getText() );
  210.                 } catch( Exception e1 ) {
  211.                     // If neither a Double or Date, assume its a String.
  212.                     objects[i] = argText[i].getText();
  213.                 }
  214.             }
  215.         }
  216.  
  217.         String result = null;
  218.         try {
  219.             result = format.format(objects);
  220.         }
  221.         catch (Exception e)
  222.         {
  223.             errorText("format threw an exception: " + e.toString());
  224.             result = "ERROR";
  225.         }
  226.         resultText.setText(result);
  227.     }
  228.  
  229.     /**
  230.      * Handles keyboard events for all text items
  231.      */
  232.     class MyKeyAdapter extends KeyAdapter {
  233.         public void keyReleased(KeyEvent evt) {
  234.         if (evt.getSource() == argText[2])  {
  235.         doFormattingEvent(evt);
  236.         } else if (evt.getSource() == argText[1])  {
  237.         doFormattingEvent(evt);
  238.         } else if (evt.getSource() == argText[0])  {
  239.         doFormattingEvent(evt);
  240.         } else if (evt.getSource() == patternText)  {
  241.         doFormattingEvent(evt);
  242.         }
  243.         }
  244.     }
  245.  
  246.     /*
  247.      * This method handles state changes that come from the locale menu
  248.      */
  249.     public void itemStateChanged(ItemEvent e) {
  250.         resetFormat();
  251.         doFormatting();
  252.     }
  253.  
  254.  
  255.     /**
  256.      * Handles window events.
  257.      */
  258.     class MyWindowAdapter extends WindowAdapter {
  259.     public void windowClosing(WindowEvent e) {
  260.             setVisible(false);
  261.             dispose();
  262.             if (applet != null) {
  263.                 applet.demoClosed();
  264.             } else
  265.         System.exit(0);
  266.     }
  267.     }
  268.  
  269.  
  270.     /**
  271.      * Called when a formatting event has occured.
  272.      */
  273.     public void doFormattingEvent(KeyEvent event) {
  274.         doFormatting();
  275.     }
  276.  
  277.     //------------------------------------------------------------
  278.     // package private
  279.     //------------------------------------------------------------
  280.  
  281.     void addWithFont(Container container, Component foo, Font font) {
  282.         if (font != null)
  283.             foo.setFont(font);
  284.         container.add(foo);
  285.     }
  286.  
  287.     //{{DECLARE_CONTROLS
  288.  
  289.     Label demoTitle;
  290.     Label creditLabel;
  291.  
  292.     TextArea resultText;
  293.     TextArea patternText;
  294.  
  295.     Choice localeMenu;
  296.     Label localeLabel;
  297.  
  298.     TextField[] argText = new TextField[3];
  299.     //}}
  300.  
  301.     //------------------------------------------------------------
  302.     // private
  303.     //------------------------------------------------------------
  304.     private void buildGUI() {
  305.  
  306.         //{{INIT_CONTROLS
  307.         setLayout(new FlowLayout(FlowLayout.CENTER,2,2));
  308.         setBackground(Utility.bgColor);
  309.  
  310.         // Main Title
  311.  
  312.         Panel titleCreditPanel = new Panel();
  313.         demoTitle=new Label("Message Format Demo", Label.CENTER);
  314.         demoTitle.setFont(Utility.titleFont);
  315.         titleCreditPanel.add(demoTitle);
  316.  
  317.         Panel creditPanel = new Panel();
  318.         creditLabel=new Label(creditString);
  319.         creditLabel.setFont(Utility.creditFont);
  320.         creditPanel.add(creditLabel);
  321.  
  322.         titleCreditPanel.add(creditPanel);
  323.  
  324.         Utility.fixGrid(titleCreditPanel,1);
  325.  
  326.         // result text
  327.  
  328.         Panel patternResultPanel = new Panel();
  329.  
  330.         addWithFont(patternResultPanel,new
  331.             Label("Result", Label.RIGHT),Utility.labelFont);
  332.         addWithFont(patternResultPanel,resultText= new
  333.             TextArea(FIELD_ROWS, FIELD_COLUMNS),Utility.editFont);
  334.         resultText.setEditable(false);
  335. //            resultText.setBackground(Color.white);
  336.  
  337.         addWithFont(patternResultPanel,new
  338.             Label("Pattern", Label.RIGHT),Utility.labelFont);
  339.         addWithFont(patternResultPanel,patternText=new
  340.             TextArea(FIELD_ROWS, FIELD_COLUMNS),Utility.editFont);
  341.  
  342.         Utility.fixGrid(patternResultPanel,2);
  343.  
  344.         // Locale and Credits Panel
  345.  
  346.         Panel localeCreditPanel = new Panel();
  347.  
  348.         localeLabel=new Label("Locale:",Label.LEFT);
  349.         localeLabel.setFont(Utility.labelFont);
  350.  
  351.         // LOCALE
  352.         localeMenu= new Choice();
  353.         localeMenu.setBackground(Utility.choiceColor);
  354.         // Stick the names of the locales into the locale popup menu
  355.         Locale displayLocale = Locale.getDefault();
  356.         for (int i = 0; i < locales.length; i++) {
  357.             if (locales[i].getCountry().length() > 0) {
  358.                 localeMenu.addItem( locales[i].getDisplayName(displayLocale) );
  359.             }
  360.         }
  361.        localeMenu.setFont(Utility.choiceFont);
  362.        localeMenu.select(Locale.US.getDisplayName());
  363.  
  364.         Panel localePanel=new Panel();
  365.         localePanel.add(localeLabel);
  366.         localePanel.add(localeMenu);
  367.         localeCreditPanel.add(localePanel);
  368.  
  369.         // PUT THE ARGUMENTS/ FORMATS into GRID
  370.         Panel allArgs = new Panel();
  371.  
  372.         addWithFont(allArgs,new Label(" "),Utility.labelFont);
  373.         addWithFont(allArgs,new Label("Arguments", Label.LEFT),
  374.                                       Utility.labelFont);
  375.         addWithFont(allArgs,new Label("0",Label.RIGHT),Utility.labelFont);
  376.         addWithFont(allArgs,argText[0]=new TextField(12),Utility.editFont);
  377.         addWithFont(allArgs,new Label("1",Label.RIGHT),Utility.labelFont);
  378.         addWithFont(allArgs,argText[1]=new TextField(12),Utility.editFont);
  379.         addWithFont(allArgs,new Label("2",Label.RIGHT),Utility.labelFont);
  380.         addWithFont(allArgs,argText[2]=new TextField(12),Utility.editFont);
  381.  
  382.         Utility.fixGrid(allArgs,2);
  383.  
  384.         add(titleCreditPanel);
  385.         add(patternResultPanel);
  386.         add(localeCreditPanel);
  387.         Panel bottomPanel = new Panel();
  388.         bottomPanel.add(allArgs);
  389.  
  390. //        Utility.fixGrid(bottomPanel,5);
  391. //        Utility.setInsets(bottomPanel,x,new Insets(20,20,2,2));
  392. //        Utility.setInsets(bottomPanel,x1,new Insets(20,20,2,20));
  393.  
  394.         add(bottomPanel);
  395.  
  396.         Panel copyrightPanel = new Panel();
  397.         addWithFont (copyrightPanel,new Label(Utility.copyright1, Label.LEFT),
  398.                      Utility.creditFont);
  399.         addWithFont (copyrightPanel,new Label(Utility.copyright2, Label.LEFT),
  400.                      Utility.creditFont);
  401.         Utility.fixGrid(copyrightPanel,1);
  402.         add(copyrightPanel);
  403.     }
  404.  
  405.     private void errorText(String s)
  406.     {
  407.         if (DEBUG)
  408.         {
  409.            System.out.println(s);
  410.  
  411.         }
  412.     }
  413.     private static final String creditString =
  414.         "v2.0, Demos";
  415.     private static final int FIELD_COLUMNS = 50;
  416.     private static final int FIELD_ROWS = 4;
  417.  
  418.     static private final int NUMBER = 0;
  419.     static private final int DATE = 1;
  420.     static private final int CHOICE = 2;
  421.     static private final int NONE = 3;
  422.  
  423.     private static final boolean DEBUG = false;
  424.  
  425.     private Locale[] locales;
  426.  
  427.     private ChoiceFormat choiceFormat;    // XXX
  428.  
  429.     //------------------------------------------------------------
  430.     // protected
  431.     //------------------------------------------------------------
  432.  
  433.     /* this must be protected so that the window adapter can access it */
  434.     protected DemoApplet applet;
  435. }
  436.